package io.yuanqi.hgtcshop.controller.share;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.yuanqi.hgtcshop.config.RedisService;
import io.yuanqi.hgtcshop.entity.vo.ResultMessage;
import io.yuanqi.hgtcshop.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 买家端,分享前的接口
 *
 * @author Chopper
 * @since 2020-12-18 16:59
 */
@Slf4j
@RestController
//@Api(tags = "买家端,分享接口")
@RequestMapping("/buyer/share")
public class ShareController {


    @Autowired
    private RedisService redisCache;

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.secret}")
    private String secret;
    @Autowired
    private WxMpService wxMpService;


    /**
     * 网页授权
     * 通过code换取网页授权access_token（该AccessToken与基础AccessToken不一样）
     */
    public final static String WEB_GET_ACCESS_TOKEN = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    public final static String WEB_GET_JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";


    /**
     * 网页授权
     * 获取用户详细信息（scope为 snsapi_userinfo）
     */
    public final static String WEB_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";


    /**
     * 获取access_token的值
     *
     * @return
     */
    @GetMapping("/getToken")
    public String getToken(String orderSn) {
        String token = "";
        String url = WEB_GET_ACCESS_TOKEN.replace("APPID", appId).replace("APPSECRET", secret);
        String body = HttpUtil.createGet(url)
                .execute()
                .body();
        log.info("获取了token,返回数据 body:{} ", body);
        JSONObject object = JSON.parseObject(body);
        //获取token
        token = object.getString("access_token");
        //失效时间
        String expires_in = object.getString("expires_in");
        //将token值的值放在redis里面
        redisCache.setKeyValue("gzh_access_token_"+orderSn, token);
        return token;
    }

    @GetMapping("/getOpenIdByCode")
    public String getOpenIdByCode(String code) {
        String url = WEB_GET_ACCESS_TOKEN.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
        log.info(".getOpenIdByCode url:{}",url);
        String body = HttpUtil.createGet(url)
                .execute()
                .body();
        log.info("获取了token,返回数据 body:{} ", body);
        JSONObject object = JSON.parseObject(body);
        //获取 openId
        String openId = object.getString("openid");
        return openId;
    }

    /**
     * 获取jsapi_ticket
     *
     * @return
     */
    @GetMapping("/getJsapiTicket")
    public String getJsapiTicket(String orderSn) {
        //获取redis里面的token
        Object access_token = redisCache.getValue("gzh_access_token_"+orderSn);
        log.info("从Redis中获取的token: {}", access_token);
        if (access_token == null) {
            access_token = getToken(orderSn);
        }
        log.info("实际使用的token:{}", access_token);
        String url = WEB_GET_JSAPI_TICKET.replace("ACCESS_TOKEN", access_token.toString());
        String body = HttpUtil.createGet(url)
                .execute()
                .body();
        log.info("获取了JsapiTicket,返回数据" + body);
        JSONObject object = JSON.parseObject(body);
        //获取ticket
        String ticket = object.getString("ticket");
        log.info("ticket:{}", ticket);
        //错误码
        Integer errcode = object.getInteger("errcode");
        if (errcode == 0) {
            //将ticket值的值放在redis里面
            redisCache.setKeyValue("gzh_ticket_"+orderSn, ticket);
        }
        return ticket;
    }

    /**
     * 签名
     */
    @GetMapping("/getSing")
    public ResultMessage<JSONObject> getSing(String url,String orderSn) {
        //从redis里面获取ticket
        Object ticket = redisCache.getValue("gzh_ticket_"+orderSn);
        log.info("ticket:{}", ticket);
        if (ticket == null) {
            ticket = getJsapiTicket(orderSn);
        }
        log.info("实际使用的ticket:{}", ticket);
        Map<String, String> ret = WeChatUtils.sign(ticket.toString(), url);
        log.info("sing:{}", ret);
        JSONObject objectData = new JSONObject();
        for (Map.Entry entry : ret.entrySet()) {
            objectData.put(entry.getKey().toString(), entry.getValue());
        }
        objectData.put("linkPage","https://buyer-api.hgtc.shop/#/pages/cart/dfPay/sharePay?orderSn="+orderSn);
//        objectData.put("MainImage","http://60.205.169.111:9000/testbuck/%E5%88%86%E4%BA%AB%E6%A0%87%E5%A4%B4.jpg?Content-Disposition=attachment%3B%20filename%3D%22%E5%88%86%E4%BA%AB%E6%A0%87%E5%A4%B4.jpg%22&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20240326%2F%2Fs3%2Faws4_request&X-Amz-Date=20240326T091804Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=21c74adc97601a805b2b94bc448e5a35743064b5a987ebd8593d410acf4a8ff5");
        objectData.put("MainImage","http://60.205.169.111:9000/testbuck/%E5%88%86%E4%BA%AB%E6%A0%87%E5%A4%B4.jpg?Content-Disposition=attachment%3B%20filename%3D%22%E5%88%86%E4%BA%AB%E6%A0%87%E5%A4%B4.jpg%22&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20240403%2F%2Fs3%2Faws4_request&X-Amz-Date=20240403T100215Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=84f4563751d6a9f418959a6fe1aeabab03e315e3a0a8cf22e5bdee730c2e1fdf");
        objectData.put("appId", appId);
        return ResultUtil.data(objectData);
    }

    @GetMapping("/getSignInfo")
    public ResultMessage<JSONObject> getSignInfo(String hrefPage,String orderSn) {
        log.info(".getSignInfo hrefPage:{} orderSn:{}", hrefPage,orderSn);
        getToken(orderSn);
        getJsapiTicket(orderSn);
//        ResultMessage<JSONObject> sing = getSing("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0fa1500017b8f6f1&redirect_uri="+hrefPage+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        ResultMessage<JSONObject> sing = getSing(hrefPage,orderSn);
        log.info(".getSignInfo result:{} ", JSON.toJSONString(sing));
        return sing;
    }


//    @GetMapping("/getOpenId")
//    public ResultMessage<JSONObject> getOpenId() {
//        getToken();
//        getJsapiTicket();
//        ResultMessage<JSONObject> sing = getSing("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7ff43cdb712fc05b&redirect_uri=https://m.kuaikuai.fun/pages/cart/dfPay/sharePay&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
//        return sing;
//    }


    /** 微信授权路由 */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("state") String state,
                            @RequestParam("url") String url){
        //这个方法的三个参数分别是授权后的重定向url、获取用户信息类型和state
        log.info(".authorize 接受到请求 state:{} url:{}",state,url);
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(
                url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(state));
        log.info("【微信网页授权】获取code,redirectUrl={}",redirectUrl);

        String body = HttpUtil.createGet(redirectUrl)
                .execute()
                .body();
        log.info("body={}",body);
        return body;
    }

}
